package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.KeyboardUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.dialog.PopupSelectFinancial;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.di.component.DaggerBasicInfoComponent;
import com.cj.mobile.iabp.mvp.contract.BasicInfoContract;
import com.cj.mobile.iabp.mvp.model.entity.AccountInfo;
import com.cj.mobile.iabp.mvp.model.entity.DeptInfo;
import com.cj.mobile.iabp.mvp.presenter.BasicInfoPresenter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * Description:基本信息
 * <p>
 * 需求：手机号不可修改。
 * 其它信息只有在状态为3时可修改。
 * <p>
 * Created by MVPArmsTemplate on 07/29/2020 18:00
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class BasicInfoActivity extends BaseActivity<BasicInfoPresenter> implements BasicInfoContract.View {

    @BindView(R.id.txvi_basicinfoactivity_username)
    EditText txviUserName;                                                                          // 姓名

    @BindView(R.id.txvi_basicinfoactivity_mobile)
    TextView txviMobile;                                                                            // 电话

    @BindView(R.id.txvi_basicinfoactivity_sex)
    TextView txviSex;                                                                               // 性别
    @BindView(R.id.txvi_basicinfoactivity_campus)
    TextView txviCampus;                                                                            // 院区

    @BindView(R.id.txvi_basicinfoactivity_department)
    TextView txviDepartment;                                                                        // 科室

    @BindView(R.id.btn_basicinfo_confim)
    Button btnSubmit;                                                                               // 提交

    @BindView(R.id.linla_basicinfoactivity_loading)
    View loading;                                                                                   // 加载效果

    // 对话框
    private MaterialDialog mDialog;
    // 性别 弹框
    private PopupSelectFinancial mPopupSex;
    // 院区 弹框
    private PopupSelectFinancial mPopupCampus;
    // 科室 弹框
    private PopupSelectFinancial mPopupDepartment;

    // 用户id
    private String id;
    // 院区id
    private String mCampusId;
    // 科室id
    private String mDepartmentId;
    // 性别：1男  2女  9其它
    private String mSexId;


    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    protected void onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        if (mDialog != null) {
            this.mDialog.dismiss();
        }
        super.onDestroy();

        this.mDialog = null;
        this.mPopupSex = null;
        this.mPopupCampus = null;
        this.mPopupDepartment = null;
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 初始化基本信息
        if (mPresenter != null) {
            mPresenter.initData();
        }
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerBasicInfoComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_basic_info;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // 设置标题
        setTitle("基本信息");
        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.common_execute).progress(true, 0).build();

        loadSex();
    }

    @OnClick({
            R.id.linla_basicinfoactivity_loading,                                                   // 加载效果
            R.id.txvi_basicinfoactivity_sex,                                                        // 性别
            R.id.txvi_basicinfoactivity_campus,                                                     // 院区
            R.id.txvi_basicinfoactivity_department,                                                 // 科室
            R.id.btn_basicinfo_confim                                                               // 提交
    })
    @Override
    public void onClick(View v) {
        super.onClick(v);
        hideInput();
        switch (v.getId()) {
            case R.id.txvi_basicinfoactivity_sex:                                                   // 性别
                if (mPopupSex != null) {
                    mPopupSex.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                }
                break;
            case R.id.txvi_basicinfoactivity_campus:                                                // 院区
                if (mPopupCampus != null) {
                    mPopupCampus.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                } else {
                    showMessage("暂无院区数据，请联系管理员！");
                }
                break;
            case R.id.txvi_basicinfoactivity_department:                                            // 科室
                if (mCampusId == null || mCampusId.equals("")) {
                    showMessage("请先选择院区！");
                } else {
                    if (mPopupDepartment != null) {
                        mPopupDepartment.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                    } else {
                        showMessage("暂无所属科室数据，请联系管理员！");
                    }
                }

                break;
            case R.id.btn_basicinfo_confim:                                                         // 提交
                String mUserName = txviUserName.getText().toString().trim();
                String mMobile = txviMobile.getText().toString().trim();

                if (TextUtils.isEmpty(mUserName)) {
                    showMessage("请填写姓名");
                    return;
                }

                if (TextUtils.isEmpty(mCampusId)) {
                    showMessage("请选择院区");
                    return;
                }

                if (TextUtils.isEmpty(mDepartmentId)) {
                    showMessage("请选择所属科室");
                    return;
                }

                if (mPresenter != null)
                    mPresenter.btnSubmit(id, mUserName, mSexId, mMobile, mCampusId, mDepartmentId);
                break;
        }
    }

    /**
     * 性别
     */
    public void loadSex() {
        List<String> mShow = new ArrayList<>();
        mShow.add("男");
        mShow.add("女");

        PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
            this.mSexId = name.equals("男") ? "1" : "2";
            txviSex.setText(name);
        };
        mPopupSex = new PopupSelectFinancial(this, "性别", mShow, itemClick);
    }

    /**
     * 加载院区
     */
    @Override
    public void loadCampus(List<DeptInfo> mList) {
        if (CommonUtils.isNotEmpty(mList)) {
            List<String> mShow = new ArrayList<>();

            for (DeptInfo info : mList) {
                mShow.add(info.getName());
            }

            PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
                DeptInfo info = mList.get(position);
                this.txviCampus.setText(CommonUtils.isEmptyReturnStr(info.getName()));
                this.mCampusId = String.valueOf(info.getId());

                this.txviDepartment.setText("");
                this.mDepartmentId = "";
                if (mPresenter != null) {
                    mPresenter.getDepartmentList(mCampusId);
                }
            };
            mPopupCampus = new PopupSelectFinancial(this, "院区", mShow, itemClick);
        }
    }

    /**
     * 加载科室
     */
    @Override
    public void loadDepartment(List<DeptInfo> mList) {
        if (CommonUtils.isNotEmpty(mList)) {
            List<String> mShow = new ArrayList<>();

            for (DeptInfo info : mList) {
                mShow.add(info.getName());
            }

            PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
                DeptInfo info = mList.get(position);
                this.txviDepartment.setText(CommonUtils.isEmptyReturnStr(info.getName()));
                this.mDepartmentId = String.valueOf(info.getId());
            };
            mPopupDepartment = new PopupSelectFinancial(this, "所属科室", mShow, itemClick);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        hideInput();
        return super.onTouchEvent(event);
    }

    /**
     * 隐藏软键盘
     */
    private void hideInput() {
        KeyboardUtils.hideSoftInput(this);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {
        if (loading != null)
            loading.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        if (loading != null)
            loading.setVisibility(View.GONE);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void hideLoadingSubmit() {
        if (mDialog != null)
            mDialog.cancel();
    }

    @Override
    public void showLoadingSubmit() {
        if (mDialog != null)
            mDialog.show();
    }

    @Override
    public void onLoadSuccess(AccountInfo info) {
        if (info != null) {
            this.id = info.getId();
            this.mCampusId = CommonUtils.isEmptyReturnStr(info.getDeptSec());
            this.mDepartmentId = CommonUtils.isEmptyReturnStr(info.getDeptId());
            this.mSexId = CommonUtils.isEmptyReturnStr(info.getSex());

            if (mPresenter != null) {
                mPresenter.getDepartmentList(mCampusId);
            }

            // 姓名
            txviUserName.setText(CommonUtils.isEmptyReturnStr(info.getName()));

            // 手机号 不可修改
            txviMobile.setText(CommonUtils.isEmptyReturnStr(info.getMobile()));

            loadSex(mSexId);

            txviCampus.setText(CommonUtils.isEmptyReturnStr(info.getSecName()));
            txviDepartment.setText(CommonUtils.isEmptyReturnStr(info.getDeptName()));
        }

    }

    /**
     * 显示性别
     */
    private void loadSex(String value) {
        if (value.equals("1")) {
            txviSex.setText("男");
        } else if (value.equals("2")) {
            txviSex.setText("女");
        } else if (value.equals("9")) {
            txviSex.setText("其它");
        } else {
            txviSex.setText("");
        }
    }
}
